#!/usr/local/bin/python  
#coding=utf-8 
#author:ywchen2000
#email:ywchen2000@gmail.com
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
from optparse import OptionParser
import urllib  
import urllib2  
import StringIO
import gzip
import sys
import os
import re
import string
import time
from xml.dom.minidom import  parseString
from multiprocessing import Process 
from mp4down import MyHttpGet
from multiprocessing.sharedctypes import Array
from ctypes import create_string_buffer


base64Str=""
base64Count = 0
END_OF_INPUT = -1
base64Chars=[
 'A','B','C','D','E','F','G','H',
 'I','J','K','L','M','N','O','P',
 'Q','R','S','T','U','V','W','X',
 'Y','Z','a','b','c','d','e','f',
 'g','h','i','j','k','l','m','n',
 'o','p','q','r','s','t','u','v',
 'w','x','y','z','0','1','2','3',
 '4','5','6','7','8','9','+','/'
]

#reverseBase64Chars={}

def setBase64Str(str):
    global base64Str
    global base64Count
    base64Str = str;
    base64Count = 0;

def  readBase64():
    global base64Str
    global END_OF_INPUT
    global base64Count
    c=0
    if  base64Str == None:  
        return END_OF_INPUT;
    if  base64Count >= len(base64Str):
        return END_OF_INPUT;
    c = ord(base64Str[base64Count]) & 0xff
    base64Count+=1;
    return c;
 
def encodeBase64(str):
    global END_OF_INPUT
    setBase64Str(str)
    result=""
    inBuffer=[0,0,0]
    lineCount = 0
    done = False
    inBuffer[0]=readBase64()
    while   (not done) and inBuffer[0]!= END_OF_INPUT:
        inBuffer[1] = readBase64();
        inBuffer[2] = readBase64();
        result += (base64Chars[ inBuffer[0] >> 2 ])
        if  inBuffer[1] != END_OF_INPUT:
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30) | (inBuffer[1] >> 4) ])
            if  inBuffer[2] != END_OF_INPUT:
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6) ])
                result += (base64Chars [inBuffer[2] & 0x3F])
            else :
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c)])
                result += '='
                done = True
        else :
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30)])
            result += ('=')
            result += ('=')
            done = true
        lineCount += 4
        if  lineCount >= 76:
            result += ('\n')
            lineCount = 0
        inBuffer[0]=readBase64()
    return result;
    
def GetDownloadFile(url):
    conn = urllib2.urlopen(url)
    if conn.headers.has_key('content-encoding'):
        fileobj = StringIO.StringIO()
        fileobj.write(conn.read())
        fileobj.seek(0)
        gzip_file = gzip.GzipFile(fileobj=fileobj)
        context = gzip_file.read()
    else:
        context = conn.read()
    return context   
        
def ParseFile(context):          
    contextlist = []
    templist = context.split("\"")
    contextlist.append(templist[1])
    contextlist.append(templist[3])
    return contextlist
    
def ParseFile2(context):
    contextlist = context.split("(")
    contextlist = contextlist[-1].split(")")   
    return contextlist[0]
    
def StartParseUrl(url):
   url = url.replace("http://", "http:##").replace("https://","https:##")
   encodeurl = "http://www.flvxz.com/getFlv.php?url=" + encodeBase64(url)
   context = GetDownloadFile(encodeurl)
   urls=re.findall("down\\(.*?\\)",context,re.I)
   for u in urls:
      urlinfo = ParseFile(u)
      aurl = urlinfo[0]
      p=Process(target=MyHttpGet, args=(aurl, 5, urlinfo[1]))
      p.start()
      while p.is_alive():
	 time.sleep(0.8)

if __name__ =="__main__":
    parser = OptionParser()
    parser.add_option("-f","--file",action="store",type="string",dest="url")
#    parser.add_option("-o","--output",action="store",type="string",dest="output")
    (options,args) =parser.parse_args(sys.argv)
    if options.url:
       StartParseUrl(options.url)
        #url = options.url
        #url = url.replace("http://", "http:##").replace("https://","https:##")
        #encodeurl = "http://www.flvxz.com/getFlv.php?url=" + encodeBase64(url)
        #context = GetDownloadFile(encodeurl)
        #urls=re.findall("down\\(.*?\\)",context,re.I)
        #for u in urls:
	  #urlinfo = ParseFile(u)
	  #aurl = urlinfo[0]
	  #p=Process(target=MyHttpGet, args=(aurl, 5, urlinfo[1]))
	  #p.start()
	  #while p.is_alive():
	      #time.sleep(0.8)

